import redis

from lib.handler.redis_handler import RedisHandler
from lib.utils.print_util import PrintUtil


class RedisFactory:
    redis = None

    @staticmethod
    def get_redis():
        if not RedisFactory.redis:
            RedisFactory.init()

        return RedisFactory.redis

    @staticmethod
    def init():
        entity = RedisHandler.redis
        try:
            if not entity.password:
                _redis = redis.StrictRedis(host=entity.host, port=entity.port, db=entity.db,
                                           decode_responses=True)
            else:
                _redis = redis.StrictRedis(host=entity.host, port=entity.port, db=entity.db, password=entity.password,
                                           decode_responses=True)

        except BaseException as e:
            PrintUtil.start("cannot start redis server, please check redis [account]")
            print(e)

        RedisFactory.redis = _redis

    @staticmethod
    def init_redis(host, port=None, db=None):

        if not port:
            port = 6379

        if not db:
            db = 2
        _redis = redis.StrictRedis(host=host, port=port, db=db, decode_responses=True)
        RedisFactory.redis = _redis
